package com.bincloud.vue.admin.web.service.api.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bincloud.vue.admin.common.constanst.SqlConstant;
import com.bincloud.vue.admin.common.enums.FlagEnum;
import com.bincloud.vue.admin.common.enums.ums.UmsUserStateEnum;
import com.bincloud.vue.admin.common.exception.BaseException;
import com.bincloud.vue.admin.common.exception.CodeMsg;
import com.bincloud.vue.admin.common.util.ObjectUtils;
import com.bincloud.vue.admin.dao.mapper.ums.UmsUserMapper;
import com.bincloud.vue.admin.model.dto.ResourceDTO;
import com.bincloud.vue.admin.model.dto.UserDTO;
import com.bincloud.vue.admin.model.entity.UmsUser;
import com.bincloud.vue.admin.web.service.api.UserService;
import com.bincloud.vue.admin.web.service.ums.IUmsUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Set;

/**
 * @Description: 用户相关接口实现
 * @Author: bincloud, mvpzhou
 * @Date: Create By bincloud, mvpzhou on 2022/2/22
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Resource
    private IUmsUserService userService;
    @Resource
    private UmsUserMapper userMapper;

    /**
     * 获取用户信息
     *
     * @param username 用户名
     * @return {@link UserDTO} 用户信息
     */
    @Override
    public UserDTO getUserDTO(String username) {
        UmsUser user = userService.getOne(Wrappers.<UmsUser>lambdaQuery().eq(UmsUser::getUsername, username).last(SqlConstant.LIMIT_1));
        if (ObjectUtils.isNull(user)) {
            throw new BaseException(CodeMsg.ACCOUNT_NOT_EXIST);
        }
        LocalDateTime now = LocalDateTime.now();
        UserDTO userDTO = new UserDTO();
        userDTO.setPassword(user.getPassword());
        userDTO.setUsername(user.getUsername());
        userDTO.setAccountNonExpired(isAfter(user.getAccountExpire(), now));
        userDTO.setAccountNonLocked(isNoLocked(user.getState()));
        userDTO.setCredentialsNonExpired(isAfter(user.getCredentialsExpire(), now));
        userDTO.setEnabled(isEnabled(user.getFlag()));
        return userDTO;
    }

    private boolean isEnabled(Integer flag) {
        return ObjectUtils.isNotNull(flag) && ObjectUtils.equals(FlagEnum.UNDELETED.getCode(), flag);
    }

    private boolean isNoLocked(Integer state) {
        return ObjectUtils.isNotNull(state) && !ObjectUtils.equals(UmsUserStateEnum.LOCKOUT.getCode(), state);
    }

    private boolean isAfter(LocalDateTime a, LocalDateTime b) {
        if (ObjectUtils.isNull(a) || ObjectUtils.isNull(b)) {
            return false;
        }
        return a.isAfter(b);
    }

    /**
     * 获取资源信息列表
     *
     * @param username 用户名
     * @return {@link ResourceDTO} 资源信息列表
     */
    @Override
    public Set<ResourceDTO> getResourceSets(String username) {
        // 获取资源列表
        return userMapper.getResourceSets(username);
    }
}
